from flask import Flask, render_template, request, session, redirect, flash
import requests
from for_sql import User_ForSql, User_Follower_ForSql
import time

app = Flask(__name__)


def get(params):
    # payload = {'key':['物理','暑期']}
    # r = requests.get("http://127.0.0.1:5000/search/key=",params=payload)
    url = "http://127.0.0.1:5000/search/key="
    for p in params:
        url += " {}".format(p)
    r = requests.get(url)
    # r.encoding = 'utf-8'
    return r

sql_info={'host':"127.0.0.1", 'port':"3306", 'user':"jmu", 'passwd':"jmu", 'database':"jmu_base"}

@app.route("/login")
def login():
    return render_template("login.html")


@app.route("/logout")
def logout():
    session['name'] = None
    return render_template("login.html")


# 验证用户密码
@app.route("/LoginServletUrl", methods=['POST'])
def LoginServletUrl():
    username = request.form['name']
    password = request.form['psw']
    F = User_ForSql(host=sql_info['host'], port=sql_info['port'], user=sql_info['user'], passwd=sql_info['passwd'], database=sql_info['database'],
                    table="user_password")
    if F.verify_user(username, password):
        session['name'] = username
        return redirect("/")
    else:
        return "<h1>Error password or Error username</h1>"


@app.route("/register")
def register():
    return render_template("register.html")


@app.route("/RegisterServletUrl", methods=['POST'])
def RegisterServletUrl():
    # TODO: 用户名提示
    # TODO：密码安全提示
    # todo：两个密码不一样提示
    username = request.form['name']
    password = request.form['psw']
    F = User_ForSql(host=sql_info['host'], port=sql_info['port'], user=sql_info['user'], passwd=sql_info['passwd'], database=sql_info['database'],
                    table="user_password")
    if not F.check_exist(username):
        F.insert_date(username, password)
        return redirect("/login")
    else:
        return "<h1>Error password or Error username</h1>"

@app.route("/reset_password")
def reset_password():
    return render_template("reset_password.html")

@app.route("/ResetPasswordServletUrl", methods=['POST'])
def ResetPasswordServletUrl():
    username = session.get('name')
    password1 = request.form['psw1']
    password2 = request.form['psw2']
    if username is None:
        return "Boom!"
    elif password1 != password2:
        return "两次密码不一样"
    F = User_ForSql(host=sql_info['host'], port=sql_info['port'], user=sql_info['user'], passwd=sql_info['passwd'], database=sql_info['database'],
                    table="user_password")
    F.update_date(username,password2)
    return redirect("/")


@app.route("/")
def index():
    # F = User_ForSql(host="127.0.0.1", port="8001", user="test_adek", passwd="123456", database="test",
    #                 table="user")
    # f = F.get_user_key(1234)
    F = User_Follower_ForSql(host=sql_info['host'], port=sql_info['port'], user=sql_info['user'], passwd=sql_info['passwd'], database=sql_info['database'],
                             table="user_subscription")
    if session.get('name') != None:
        f = F.get_follower(session.get('name'))
        print(f)
        if f == set():
            return render_template("index.html", infos="", follows="")
        else:
            r = get(f).json()
            r = sort_time(r)
            for i in r:
                i[2] = time.strftime("%Y-%m-%d", time.localtime(i[2]))
            return render_template("index.html", infos=r, follows=f)
    else:
        r = get("院").json()
        r = sort_time(r)
        for i in r:
            i[2] = time.strftime("%Y-%m-%d", time.localtime(i[2]))
        return render_template("index.html", infos=r, follows="")


def sort_time(ll):
    if len(ll) == 0:
        return []
    temp = ll[0]
    left = []
    right = []
    for i in ll[1:]:
        if i[2] > temp[2]:
            left.append(i)
        else:
            right.append(i)
    return sort_time(left) + [temp] + sort_time(right)


@app.route("/add_follower")
def add_follower():
    return render_template("add_follower.html")


@app.route("/AddFollowerServletUrl", methods=["POST"])
def AddFollowerServletUrl():
    new_follower = request.form['follower']
    F = User_Follower_ForSql(host=sql_info['host'], port=sql_info['port'], user=sql_info['user'], passwd=sql_info['passwd'], database=sql_info['database'],
                             table="user_subscription")
    user_name = session.get('name')
    f = F.get_follower(user_name)

    if new_follower in f:
        flash("提交失败，已经有了相同的关注")
        return redirect("/add_follower")
    else:
        F.insert_new_follower(user_name, new_follower)
        flash("提交成功！正在返回主页")
        return redirect("/")


@app.route("/DelFollowerServletUrl/key=<keyword>")
def DelFollowerServletUrl(keyword):
    F = User_Follower_ForSql(host=sql_info['host'], port=sql_info['port'], user=sql_info['user'], passwd=sql_info['passwd'], database=sql_info['database'],
                             table="user_subscription")
    user_name = session.get('name')
    if user_name is None:
        return "Bang!"
    F.del_follower(user_name, keyword)
    return redirect("/")


app.secret_key = "A0Zr98j/3yX R~XHH!jmN]LWX/,?RT"
if __name__ == "__main__":
    app.run()
